package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.command;

import java.util.ArrayList;
import java.util.List;

import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;

public abstract class AbstractCommand implements Command {

	private int state = Command.NOT_EXECUTING;
	private int address;
	private List<CommandListener> listeners = new ArrayList<CommandListener>();
	
	public AbstractCommand(){
	}
	@Override
	abstract public boolean needRetrieve();

	@Override
	abstract public ModbusRequest getRetriveRequest() throws CommandException;

	@Override
	abstract public void setRetrieveResponse(ModbusResponse res) throws CommandException;

	@Override
	abstract public ModbusRequest getCommandRequest();

	@Override
	synchronized public void setState(int newstate) {
		this.state = newstate;
		for (CommandListener listener : listeners) {
			listener.CommandEvent();
		}
	}
	
	@Override
	synchronized public int getState(){
		return this.state;
	}

	/**
	 * @return the direction
	 */
	public int getAddress() {
		return address;
	}

	/**
	 * @param direction the direction to set
	 */
	public void setAddress(int address) {
		this.address = address;
	}
	
	public void addCommandListener(CommandListener cmdlistener){
		if(!listeners.contains(cmdlistener))
			listeners.add(cmdlistener);
	}
	
	public void removeCommandListener(CommandListener cmdlistener){
		if(listeners.contains(cmdlistener))
			listeners.remove(cmdlistener);
	}

}
